<?php
namespace V1\Controller;
use Common\Library\Exception\BadRequest;
/**
 * 常用操作控制类
 *
 * 短信相关：发送
 *     
 * @author wangzhenxian
 * @package application.components 
 */
class UtilController extends BaseController {
    
    protected $errorCode = array(
        'sendsms' => array(
            '-1' => '短信发送频度在120秒',
            '-2' => '短信写入数据库' ,
            '-3' => '短信发送不成功' ,
        ),
         'feedback' => array(
            '-1' => '用户不存在' ,
            '-2' => '反馈意见写入失败' ,
        ),
        'invite' => array(
            '-1'=>'用户token失效或有误',
        ),
    );
    
    public function index(){
        
    }
    
    /**
     * start-image图像分辨率接受如下格式：
     * 
     * 320*432
     * 480*728
     * 720*1184
     * 1080*1176
     * 
     */
    public function startImage($resolution=NULL) {
        $data = array("code" => 0,"msg" => "","info"=>array());
        if(isset($resolution) && array_key_exists($resolution, C('START_IMAGE'))){
            $data['info']['imgs']=C("START_IMAGE")[$resolution];
        }  else {
            $data['info']['imgs']=C("DEFAULT_START_IMAGE");
        }
        $data['info']['copyright']='© 涨跌幅';//显示图片版权信息
        $this->responseResult($data);
    }
    /**
     * 检查版本升级
     * n1.n2.n3
     * n3 更新紧急修复bug 不涉及前端页面
     * n2 常规升级 bug修复 功能完善涉及前端页面
     * n1 重大版本升级 新增功能
     */
    public function checkversion($os=NULL,$version=NUll){
        
        $data = array("code" => 0,"msg" => "","info"=>array()); 
        
        $client_version= null;
        $current_version= null;
        
        if(strstr($os,'iPhone')){
            $client_version = C('IOS_VERSION')[$version];
            $current_version = C('CURRENT_IOS_VERSION');
        } else {
            $client_version = C('ANDROID_VERSION')[$version];
            $current_version = C('CURRENT_ANDROID_VERSION');
        }
        if(empty($client_version['versionCode'])){
            $data["msg"] = "获取不到最新版本，请稍后重试";
        }else if($client_version['versionCode']< $current_version['versionCode'] ) {
            $result =  intval($current_version['versionCode']/10)-intval($client_version['versionCode']/10);
            if($result>0){
                $data['msg'] = "发现一个新版本{$current_version['version']}：\n{$current_version['desc']}";
                $data["info"]['title'] = "新版本更新";
                $data['info']['url']='http://xxxxxx/aaa.apk';  
            }else{
                 $data["msg"] = "已是最新版本";
            }
        }else if($client_version['versionCode']==$current_version['versionCode']){
             $data["msg"] = "当前版本号:{$current_version['version']}已是最新版本";
        }
        
        $this->responseResult($data);
    }
    /**
     * 帮助中心
     */
    public function help(){
        //返回一个URL
    }
    /**
     * 关于我们
    */
    public function aboutus(){
        //返回一个URL
    }
    /**
     * 意见反馈
     */
    public function feedback(){
      if(!IS_POST){
            throw new BadRequest("该方法只支持POST请求", 1);
      }
      $data = array("code" => 0,"msg" => "","info"=>array()); 
      $content = I('post.content','');
        
      if(empty($content) || mb_strlen($content, 'utf-8')>200){
            throw new BadRequest("参数异常", 1);
       }
      
      list($uid,$user_token) = $this->checkUserToken();
      
      $feedback_data = ['user_id'=>$uid,'content'=>$content,'create_time'=>NOW_TIME,'status'=>1];
      if($this->save('CommonFeedback',$feedback_data )){
          return $this->responseResult($data);
      }else{
          return $this->responseError('-2');
      }
      
      
    }
    
    public function sendSms(){
       if(!IS_POST){
             throw new BadRequest("该方法只支持POST请求", 1);
       }
       $data = array("code" => 0,"msg" => "","info"=>array());
       $phonenumber = I('post.n','','/^\d{11}$/');
       if(empty($phonenumber)){
            throw new BadRequest("参数异常", 1);
       }
       
       $smsModel = D('Sms');
       //是否已经在可重复发送短信的时间内发送过短信
       if($smsModel->checkRepeatSms($phonenumber)){
            $this->responseError(-1);
       }else{
            //生成短信验证码
            //$code = mt_rand(1000, 9999);
            $code=2468; //便于测试后期修改
            $sms_content_template = "您的验证码为：%s，请在10分钟内完成校验，如非本人操作，请忽略本短信。【涨跌福】";
            $sms_content =  sprintf($sms_content_template, $code);
            //写短信表
            $result = $smsModel->addSms($phonenumber,$code,$sms_content);
            empty($result) && $this->responseError(-2);

            //发送短信调用第三方短信接口
            //$error_code = sms($phonenumber,$sms_content);
            $error_code='1223333';//便于测试后期修改
            if(strlen($error_code)>3){
                //更新短信表中短信发送状态
                $smsModel->updateStatus($result,1);
                $data['info']['msg'] ='已发送短信至'.substr_replace($phonenumber, '****', 3,4);
                $this->responseResult($data);
            }else{
                $smsModel->updateStatus($result,$error_code);
                $this->responseError(-3);
            }
       }
    }
    
    
   /**
    * 邀请好友接口
    * @author 尹雷
    */
   public function invite() {
           list($uid,$user_token) = $this->checkUserToken();
           $data = array("code" => 0,"msg" => "","info"=>array());
           $url = U('/App', array('recommenderId' => $uid), true, true);
           //$count = M('UserTask')->where(array('user_id' => $uid, 'task_type' => 'invite'))->count();
           $friends = D('Friends')->where(array('user_id' => $uid, 'src' => 2))->select();
           $count = count($friends);
           $money = bcmul($count, 3, 2);
           $data['info']['url'] = $url;
           $data['info']['count'] = $count;
           $data['info']['money'] = $money;
           $this->responseResult($data);
   }
}